import { CardCategory, CardCategoryList, TriggerType, TriggerTypeList, UaCard } from "../../../models/ua-card.model";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { UaUserDeckDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";
import { formatDate } from "../../../utils/util";

let rewardedVideoAd: WechatMiniprogram.RewardedVideoAd | null = null

// pages/user/user-deck-detail/user-deck-detail.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    CND_HOST: GlobalService.FILE_HOST,
    STATIC_FILE_HOST: GlobalService.STATIC_FILE_HOST,
    qrcode: '',
    idCountMap: {} as { [key: number]: number },
    characterList: [] as UaCard[],
    eventList: [] as UaCard[],
    fieldList: [] as UaCard[],
    showWarnConfirm: false,
    deckName: "",
    logo: "",
    userNickName: "",
    energyCountMap: {} as { [key: string]: number },
    energyTypeKeys: [] as string[],
    categoryCountMap: {} as { [key: string]: number },
    categoryTypeKeys: [] as string[],
    triggerCountMap: {} as { [key: string]: number },
    triggerTypeKeys: [] as string[],
    total: 0,
    totalTrigger: 0,
    myDeck: false,
    r0: '',
    r1: '',
    cr0: '',
    cr1: '',
    ranked: false,
    description: '',
    detailVisible: false,
    detailCard: {} as UaCard,
    max: 0,
    coverCardList: [] as string[],
    deckCardImgList: [] as string[]
  },

  customData: {
    ipId: undefined as number | undefined,
    deckId: undefined as number | undefined,
    authorId: undefined as number | undefined,
    idCountMap: {} as { [key: number]: number },
    cardDeckNoCountMap: {} as { [key: string]: number },
    energyCountOrderMap: {} as { [key: string]: number },
    cardList: [] as UaCard[],
    colorCount: 0,
    finalCount: 0,
    specialCount: 0,
    c0: 0,
    c1: 0,
    needEffect: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    this.customData.ipId = options.ipId;
    this.customData.deckId = options.deckId;
    wx.setNavigationBarTitle({
      title: '卡组详情'
    });
    this.showAd();


    UaIpService.fetchUaIp(options.ipId).then((response: UaIpEntity) => {
      if (response) {
        this.setData({
          logo: response.ipTitleLogo
        });
      }
    })
    const categoryCountMap: { [key: string]: number } = {};
    const categoryTypeKeys: string[] = [];
    for (const item of CardCategoryList) {
      categoryTypeKeys.push(item.value.toString().toLowerCase());
      categoryCountMap[item.value.toString().toLowerCase()] = 0;
    }
    const triggerCountMap: { [key: string]: number } = {};
    const triggerTypeKeys: string[] = [];
    for (const item of TriggerTypeList) {
      triggerTypeKeys.push(item.value.toString().toLowerCase());
      triggerCountMap[item.value.toString().toLowerCase()] = 0;
    }

    this.setData({
      categoryTypeKeys,
      categoryCountMap,
      triggerTypeKeys,
      triggerCountMap
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initDeck();
  },

  initDeck() {
    UserDeckService.findById(this.customData.deckId!).then((response: UaUserDeckDto) => {
      if (response) {
        UserDeckService.getQrCode(response.sn!).then((qrcode: string) => {
          this.setData({
            qrcode: qrcode ?? ''
          })
        });
        this.customData.cardList = response.cardDtoList ?? [];
        const cardMap: { [key: number]: UaCard } = {}
        this.customData.cardList.map((card: UaCard) => {
          cardMap[card.id!] = card;
        })
        const idCountMap: { [key: number]: number } = {};
        const cardDeckNoCountMap: { [key: string]: number } = {};
        for (const item of response.cardList ?? []) {
          idCountMap[item.id!] = item.count!;
          const card = cardMap[item.id!];
          if (card) {
            if (!cardDeckNoCountMap[card.cardDeckNo!]) {
              cardDeckNoCountMap[card.cardDeckNo!] = 0;
            }
            cardDeckNoCountMap[card.cardDeckNo!] += item.count!;
          }
        }
        this.customData.idCountMap = idCountMap;
        this.customData.cardDeckNoCountMap = cardDeckNoCountMap;
        this.customData.authorId = response.userId;
        let coverCardList: string[] = []
        if (!!response.cover) {
          coverCardList = response.cover.split(';');
        }
        this.setData({
          deckName: response.name,
          userNickName: response.userNickName + ' ' + formatDate(new Date(response.updateDate ?? Date.now())),
          myDeck: LocalStorage.getUserInfo()?.id === response.userId,
          ranked: response.ranked,
          description: response.description,
          coverCardList
        })
        this.refreshInfo();
      }
    })
  },

  refreshInfo() {
    const deckNos: string[] = [];
    const characterList: UaCard[] = [];
    const eventList: UaCard[] = [];
    const fieldList: UaCard[] = [];
    const triggerCountMap: { [key: string]: number } = {};
    const categoryCountMap: { [key: string]: number } = {};
    const energyCountMap: { [key: string]: number } = {};
    const energyTypeCountMap: { [key: string]: number } = {};
    const energyTypeKeys: string[] = [];
    const energeColorMap: { [key: string]: string } = {};
    let total = 0;
    let totalTrigger = 0;
    let c0 = 0;
    let c1 = 0;
    const deckCardImgList: string[] = [];
    for (const card of this.customData.cardList) {
      if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
        deckNos.push(card.cardDeckNo!);
        const c = this.customData.cardDeckNoCountMap[card.cardDeckNo!];
        if (card.triggerType) {
          if (!triggerCountMap[card.triggerType.toString().toLowerCase()]) {
            triggerCountMap[card.triggerType.toString().toLowerCase()] = 0;
          }
          triggerCountMap[card.triggerType.toString().toLowerCase()] += c;
          totalTrigger += c;
        }
      }
      if (!!this.customData.idCountMap[card.id!]) {
        deckCardImgList.push(card.cardImg!.replace('.png', '.jpg'));
        switch (card.cardCategory) {
          case CardCategory.Character:
            characterList.push(card);
            break;
          case CardCategory.Event:
            eventList.push(card);
            break;
          case CardCategory.Field:
            fieldList.push(card);
            break;
        }
        if (card.cardCategory) {
          if (!categoryCountMap[card.cardCategory.toString().toLowerCase()]) {
            categoryCountMap[card.cardCategory.toString().toLowerCase()] = 0;
          }
          categoryCountMap[card.cardCategory.toString().toLowerCase()] += this.customData.idCountMap[card.id!];
          total += this.customData.idCountMap[card.id!];
        }
        const ek = `${card.needEnergyType!.toLowerCase() + card.needEnergyCount!}`;
        energeColorMap[ek] = card.needEnergyType!.toString();
        if (!energyCountMap[ek]) {
          energyCountMap[ek] = 0;
        }
        if (!energyTypeKeys.includes(ek)) {
          energyTypeKeys.push(ek)
          this.customData.energyCountOrderMap[ek] = card.needEnergyCount!;
        }
        energyCountMap[ek] += this.customData.idCountMap[card.id!];
        if (!energyTypeCountMap[card.needEnergyType!]) {
          energyTypeCountMap[card.needEnergyType!] = 0;
        }
        energyTypeCountMap[card.needEnergyType!] += this.customData.idCountMap[card.id!];
        if (card.needEnergyCount === 0) {
          c0 += this.customData.idCountMap[card.id!];
        }
        if (card.needEnergyCount === 1) {
          c1 += this.customData.idCountMap[card.id!];
        }
        this.customData.c0 = c0;
        this.customData.c1 = c1;
      }
    }
    energyTypeKeys.sort((a, b) => this.customData.energyCountOrderMap[a] - this.customData.energyCountOrderMap[b]);
    let max = 0;
    for (const k of energyTypeKeys) {
      max = Math.max(+energyCountMap[k], max);
    }
    this.customData.finalCount = !!triggerCountMap[TriggerType.Final.toLowerCase()] ? triggerCountMap[TriggerType.Final.toLowerCase()] : 0;
    this.customData.colorCount = !!triggerCountMap[TriggerType.Color.toLowerCase()] ? triggerCountMap[TriggerType.Color.toLowerCase()] : 0;
    this.customData.specialCount = !!triggerCountMap[TriggerType.Special.toLowerCase()] ? triggerCountMap[TriggerType.Special.toLowerCase()] : 0;
    const coverCardList = this.data.coverCardList.filter((item) => deckCardImgList.includes(item));
    this.setData({
      characterList,
      eventList,
      fieldList,
      idCountMap: this.customData.idCountMap,
      categoryCountMap,
      triggerCountMap,
      total,
      totalTrigger,
      energyCountMap,
      energyTypeKeys,
      energeColorMap,
      max,
      coverCardList,
      deckCardImgList
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },


  test(e: any) {
    wx.showActionSheet({
      itemList: ['内战模拟', '对战模拟', '(旧版)抽牌模拟'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.deckTest()
            break;
          case 1:
            this.battleTest();
            break;
          case 2:
            this.drawTest();
            break;
        }
      },
      fail: () => { }
    })
  },


  drawTest() {
    wx.navigateTo({
      url: `/pages/user/deck-test/deck-test.page?ipId=${this.customData.ipId}&deckId=${this.customData.deckId}`,
    });
  },


  deckTest() {
    wx.navigateTo({
      url: `/pages/user/deck-battle-test/deck-battle-test.page?deckId1=${this.customData.deckId}`,
    });
  },

  battleTest() {
    wx.navigateTo({
      url: `/pages/user/user-deck-list/user-deck-list.page?deckId=${this.customData.deckId}`,
    });
  },

  edit() {
    console.log(this.customData.ipId)
    wx.navigateTo({
      url: `/pages/user/user-deck-add/user-deck-add.page?ipId=${this.customData.ipId}&deckId=${this.customData.deckId}`,
    });
  },

  showAd() {
    if (wx.createRewardedVideoAd) {
      rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-49eac4179b6d8a18'
      });
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      });
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      });
      rewardedVideoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励
          this.print();
        } else {
          // 播放中途退出，不下发游戏奖励
        }
      })

    }
  },

  print() {
    wx.showLoading({
      title: '加载中……'
    })
    setTimeout(() => {
      // const effect = GlobalService.EFFECT_CACHE[`${this.customData.deckId}`] ?? {};
      UserDeckService.genPdf(
        `${this.customData.deckId}`,
        this.customData.needEffect
      ).then(response => {
        wx.hideLoading()
        if (response && response.url) {
          wx.showLoading({
            title: '下载中……'
          })
          wx.downloadFile({
            // 示例 url，并非真实存在
            url: `${GlobalService.STATIC_FILE_HOST}${response.url}`,
            success: function (res) {
              const filePath = res.tempFilePath
              wx.openDocument({
                filePath, showMenu: true,
                complete: function () {
                  wx.hideLoading()
                }
              })
            }
          })
        }
      })
    }, 1000);
  },

  genPdf(needEffect: boolean) {
    this.customData.needEffect = needEffect;
    if (rewardedVideoAd) {
      rewardedVideoAd.show().catch(() => {
        // 失败重试
        rewardedVideoAd!.load()
          .then(() => rewardedVideoAd!.show())
          .catch(err => {
            console.error('激励视频 广告显示失败', err);
            this.print()
          })
      })
    }
  },

  // genPdfWithoutEffect() {
  //   this.customData.needEffect = false;
  //   if (rewardedVideoAd) {
  //     rewardedVideoAd.show().catch(() => {
  //       // 失败重试
  //       rewardedVideoAd!.load()
  //         .then(() => rewardedVideoAd!.show())
  //         .catch(err => {
  //           console.error('激励视频 广告显示失败', err);
  //           this.print()
  //         })
  //     })
  //   }
  // },

  duplicate() {
    wx.navigateTo({
      url: `/pages/user/user-deck-add/user-deck-add.page?duplicate=1&ipId=${this.customData.ipId}&deckId=${this.customData.deckId}`,
    });
  },

  remove() {
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          this.removeDeck();
        }
      }
    });
  },

  removeDeck() {
    UserDeckService.removeById(this.customData.deckId!).then(() => {
      wx.navigateBack();
    })
  },

  share() {
    wx.navigateTo({
      url: `/pages/tools/deck-img-share/deck-img-share.page?ipId=${this.customData.ipId}&deckId=${this.customData.deckId}`,
    });
  },

  sheet() {
    wx.navigateTo({
      url: `/pages/tools/deck-sheet/deck-sheet.page?ipId=${this.customData.ipId}&deckId=${this.customData.deckId}`,
    });
  },

  pCalc() {
    wx.navigateTo({
      url: `/pages/tools/p-calc/p-calc.page?c0=${this.customData.c0}&c1=${this.customData.c1}`,
    });
  },

  tts() {
    let result = '';
    for (const card of this.data.characterList) {
      result += `${this.data.idCountMap[card.id!]} x ${card.cardDeckNo!.replace('-P-', 'PR-1-')}\n`
    }
    for (const card of this.data.fieldList) {
      result += `${this.data.idCountMap[card.id!]} x ${card.cardDeckNo!.replace('-P-', 'PR-1-')}\n`
    }
    for (const card of this.data.eventList) {
      result += `${this.data.idCountMap[card.id!]} x ${card.cardDeckNo!.replace('-P-', 'PR-1-')}\n`
    }
    wx.setClipboardData({
      data: result,
      success() {
        wx.showToast({
          title: '导出成功',
        });
      }
    });
  },

  uasim() {
    let result = '';
    for (const card of this.data.characterList) {
      result += `${this.data.idCountMap[card.id!]}x${card.packNo}_${card.cardDeckNo}\n`
    }
    for (const card of this.data.fieldList) {
      result += `${this.data.idCountMap[card.id!]}x${card.packNo}_${card.cardDeckNo}\n`
    }
    for (const card of this.data.eventList) {
      result += `${this.data.idCountMap[card.id!]}x${card.packNo}_${card.cardDeckNo}\n`
    }
    wx.setClipboardData({
      data: result,
      success() {
        wx.showToast({
          title: '导出成功',
        });
      }
    });
  },

  openDetail(e: any) {
    for (const card of this.customData.cardList) {
      if (card.id === e.detail) {
        this.setData({
          detailVisible: true,
          detailCard: card
        });
        break;
      }
    }
  },

  onDetailVisibleChange(e: any) {
    this.setData({
      detailVisible: e.detail.visible,
    });
  },

  onPrev(e: any) {
    const cardList = [... this.data.characterList, ... this.data.fieldList, ...this.data.eventList];
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < cardList.length; i++) {
      if (detailCardId === cardList[i].id) {
        p = i;
        break;
      }
    }
    if (p === 0) {
      p = cardList.length - 1;
    } else {
      p--;
    }
    this.setData({
      detailCard: cardList[p]
    })
  },

  onNext(e: any) {
    const cardList = [... this.data.characterList, ... this.data.fieldList, ...this.data.eventList];
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < cardList.length; i++) {
      if (detailCardId === cardList[i].id) {
        p = i;
        break;
      }
    }
    if (p === cardList.length - 1) {
      p = 0;
    } else {
      p++;
    }
    this.setData({
      detailCard: cardList[p]
    })
  },

  actions() {
    wx.showActionSheet({
      itemList: ['概率计算', '导出银龙TTS卡组', '导出UASIM卡组', '生成比赛卡表', '生成原图代卡', '生成中文贴条代卡'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.pCalc();
            break;
          case 1:
            this.tts();
            break;
          case 2:
            this.uasim();
            break;
          case 3:
            this.sheet();
            break;
          case 4:
            this.genPdf(false);
            break;
          case 5:
            this.genPdf(true);
            break;
        }
      },
      fail: () => { }
    })
  },

  handleSelected() {

  }

})